package jp.ddo.trismegistos.timer.activity;

import java.util.Calendar;

import jp.ddo.trismegistos.timer.R;
import jp.ddo.trismegistos.timer.data.CountTime;
import jp.ddo.trismegistos.timer.service.ToastService;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TimerActivity extends Activity {

	private CountTime countTime;

	private TextView textView;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timer);

		textView = (TextView) findViewById(R.id.settingView);

		setSettingButtonAction();
		setTimerStartButtonAction();
	}

	@Override
	public void onActivityResult(final int requestCode, final int resultCode,
			final Intent data) {
		final int id = data.getIntExtra(getString(R.string.timeSettingKey), 0);
		final CountTime countTime = CountTime.get(id);
		if (countTime == null) {
			// TODO
		}
		this.countTime = countTime;
		textView.setText(countTime.getDispName());
	}

	protected void setSettingButtonAction() {
		final Button button = (Button) findViewById(R.id.timeSettingButton);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				final Intent intent = new Intent(getApplicationContext(),
						TimeSettingActivity.class);
				startActivityForResult(intent, 0);
			}
		});
	}

	protected void setTimerStartButtonAction() {
		final Button button = (Button) findViewById(R.id.timerStart);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				final Intent intent = new Intent(TimerActivity.this,
						ToastService.class);
				intent.putExtra(getString(R.string.timeMessageKey), "echo");
				final PendingIntent sender = PendingIntent.getService(
						TimerActivity.this, 0, intent, 0);

				final Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(System.currentTimeMillis());
				cal.add(Calendar.MINUTE, countTime.getTime());

				final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
			}
		});
	}
}
